package cn.kgc.springboot06.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONUtil;
import cn.kgc.springboot06.entity.User;
import cn.kgc.springboot06.service.UserService;
import cn.kgc.springboot06.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: mosin
 * @version: v1.0  2023/1/5
 */
@RestController
@RequestMapping("user")
//@CrossOrigin
public class UserController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;
    //生成验证码
    @RequestMapping("getCode")
    public Map  getCode(HttpSession session){
        HashMap<String, String> map = new HashMap<>();
        LineCaptcha lineCaptcha = new LineCaptcha(110, 50, 4, 5);
        String code = lineCaptcha.getCode();
        String id = session.getId();
        redisUtil.setValue(id,code,50, TimeUnit.SECONDS);
        map.put("code", code);
        map.put("msg", "请在50s之内完成登录操作");
        return map;
    }


    @RequestMapping("login")
    public Map  login(HttpSession session,String code) {
        HashMap<String, Object> map = new HashMap<>();
        String id = session.getId();
        // 从redis中获取验证码
        String value = redisUtil.getValue(id);
        System.out.println(" redis code value = " + value);

        if(value==null){
            map.put("code", 500);
            map.put("msg", "验证码失效，请刷新");
        }else{
            if(value.equals(code)){
                map.put("code", 200);
                map.put("msg", "验证码正确");
            }else{
                map.put("code", 500);
                map.put("msg", "验证码错误");
            }
        }
        return  map;
    }

    @RequestMapping("list")
    public Map getList(){
        HashMap<String, String> map = new HashMap<>();
        String userlist = redisUtil.getValue("userlist");
        if(userlist==null){
            List<User> list = userService.list();
            String s = JSONUtil.toJsonStr(list);
            redisUtil.setValue("userlist", s);
            map.put("result", s);
            map.put("msg", "数据结果来自mysql数据库");
        }else{
            map.put("result", userlist);
            map.put("msg", "数据结果来自redis数据库");
        }
        return  map;
    }

    @RequestMapping("delete")
    public String delete(Integer id){
        boolean b = userService.removeById(id);
        if(b){
            //redis缓存清空
            Boolean aBoolean = redisUtil.hasKey("userlist");
            if(aBoolean){
                redisUtil.deleteByKey("userlist");
            }
        }
        return "ok";
    }

}
